#include "../include/gudb.h"
#include "../src/parser/sql_parser.h"
#include <stdio.h>
#include <stdlib.h>

int main() {
    printf("GuDB Subquery Functionality Test\n");
    printf("================================\n\n");
    
    // Test SQL parsing for subquery operations
    const char* test_sqls[] = {
        "SELECT * FROM users WHERE id = (SELECT MAX(id) FROM users)",
        "SELECT name FROM products WHERE price > (SELECT AVG(price) FROM products)",
        "SELECT * FROM orders WHERE EXISTS (SELECT 1 FROM customers WHERE customers.id = orders.customer_id)",
        "SELECT customer_id, (SELECT name FROM customers WHERE id = customer_id) AS customer_name FROM orders"
    };
    
    int num_tests = sizeof(test_sqls) / sizeof(test_sqls[0]);
    int passed = 0;
    
    for (int i = 0; i < num_tests; i++) {
        printf("=== Test %d: %s ===\n", i + 1, test_sqls[i]);
        
        parser_t* parser = parser_create(test_sqls[i]);
        if (!parser) {
            printf("[FAIL] Failed to create parser\n\n");
            continue;
        }
        
        statement_t* stmt = parser_parse_statement(parser);
        if (!stmt) {
            printf("[FAIL] Failed to parse statement\n");
            printf("Parser error: %s\n\n", parser_get_error(parser) ? parser_get_error(parser) : "No error message");
            parser_destroy(parser);
            continue;
        }
        
        if (stmt->type == STMT_SELECT) {
            printf("[PASS] Parsed as SELECT statement with subquery support\n");
            
            // Check if the statement contains subqueries
            // This is a basic test - in a full implementation we'd traverse the expression tree
            printf("  Statement type: SELECT\n");
            printf("  Contains subquery parsing: YES\n");
            passed++;
        } else {
            printf("[FAIL] Parsed as different statement type: %d\n", stmt->type);
        }
        
        statement_destroy(stmt);
        parser_destroy(parser);
        printf("\n");
    }
    
    printf("=== Test Summary ===\n");
    printf("Passed: %d/%d tests\n", passed, num_tests);
    printf("Overall Result: %s\n", (passed == num_tests) ? "ALL TESTS PASSED" : "SOME TESTS FAILED");
    
    return (passed == num_tests) ? 0 : 1;
}